package com.example.business.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@Slf4j
@CrossOrigin("*")
@RestController
public class LoginController {

    @GetMapping("day/one")
    public String dayOne() {
        return "张恒，加油！";
    }

    @PostMapping("/login")
    public String login(
            // 接收表单中name="username"的参数，required=true表示必填
            @RequestParam("username") String username,
            // 接收表单中name="password"的参数
            @RequestParam("password") String password
    ) {
        // 这里可以添加验证用户名密码的逻辑（比如和数据库比对）
        System.out.println("登录用户：" + username + "，密码：" + password);

        // 验证通过后返回登录成功信息
        return username + " login-success 登录成功";
    }

    @RequestMapping(value = "/login-success")
    public String loginSuccess() {
        return getUsername() + " login-success 登录成功";
    }

    /**
     * 测试资源1
     */
    @GetMapping(value = "/admin/p1")
    @PreAuthorize("hasRole('admin')")
    public String r1() {
        return " /admin/p1 " + getUsername() + "访问资源1";
    }

    /**
     * 测试资源
     */
    @GetMapping(value = "/user/p2")
//    @PreAuthorize("hasAuthority('p2')")//拥有p2权限才可以访问
    public String r2() {
        return "/user/p2 " + getUsername() + "访问资源2";
    }

    // 获取当前用户信息
    private String getUsername() {
        String username = null;
        // 当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 用户身份
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            username = "匿名";
        }
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }
}
